package com.x.servlet;

import com.x.bean.User;
import com.x.service.user.UserService;
import com.x.service.user.UserServiceImpl;
import com.x.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Servlet:控制层，调用业务层代码
 * 用户登陆控制层
 * @author 13925
 */
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Login--start");
        //获取用户和密码
        String code = req.getParameter("code");
        String password = req.getParameter("password");
        //获取等级身份
        int grade = Integer.parseInt(req.getParameter("grade"));
        UserService userService = new UserServiceImpl();
        User user = userService.login(code, password, grade);
        System.out.println(code);
        System.out.println(password);
        if (user != null) {
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            /**
             * 成功就能跳转
             * 然后判断身份等级，跳转到各个页面
             */
                if (grade == 1) {
                    resp.sendRedirect("jsp/frameAdmin.jsp");
                } else {
                    resp.sendRedirect("jsp/frameStudent.jsp");
                }
        } else {
            //否则查无此人，跳转到登陆页面，并报登陆错误
            req.setAttribute("error","登陆失败，用户名或密码错误");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
